import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import MainLayout from '@/layout/MainLayout.vue'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/LoginView.vue'),
            meta: {
                requiresAuth: false,
                title: '登录'
            }
        },
        {
            path: '/',
            component: MainLayout,
            redirect: '/home',
            meta: {
                requiresAuth: true
            },
            children: [
                {
                    path: '/home',
                    name: 'home',
                    component: () => import('../views/HomeView.vue'),
                    meta: {
                        requiresAuth: true,
                        title: '首页'
                    }
                },
                {
                    path: '/about',
                    name: 'about',
                    component: () => import('../views/AboutView.vue'),
                    meta: {
                        requiresAuth: true,
                        title: '关于系统'
                    }
                },
                // 学生管理路由
                {
                    path: '/students/list',
                    name: 'students-list',
                    component: () => import('../views/students/StudentList.vue'),
                    meta: {
                        requiresAuth: true,
                        title: '学生列表'
                    }
                },
                // 班级管理路由
                {
                    path: '/class/list',
                    name: 'class-list',
                    component: () => import('../views/class/ClassList.vue'),
                    meta: {
                        requiresAuth: true,
                        title: '班级管理'
                    }
                },
                // 宿舍管理路由
                {
                    path: '/dormitory/list',
                    name: 'dormitory-list',
                    component: () => import('../views/dormitory/DormitoryList.vue'),
                    meta: {
                        requiresAuth: true,
                        title: '宿舍列表'
                    }
                },
                {
                    path: '/dormitory/building',
                    name: 'dormitory-building',
                    component: () => import('../views/dormitory/BuildingManage.vue'),
                    meta: {
                        requiresAuth: true,
                        title: '楼栋管理'
                    }
                }
            ]
        }
    ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const authStore = useAuthStore()
    
    // 检查登录状态（从 localStorage 恢复状态）
    authStore.checkAuth()
    
    const isLoggedIn = authStore.isLoggedIn

    // 设置页面标题
    if (to.meta.title) {
        document.title = `${to.meta.title} - 宿舍管理系统`
    }

    console.log('路由守卫:', {
        to: to.name,
        from: from.name,
        isLoggedIn,
        requiresAuth: to.meta.requiresAuth,
        token: authStore.token ? '有token' : '无token'
    })

    // 如果路由需要认证
    if (to.meta.requiresAuth) {
        if (isLoggedIn) {
            // 已登录，允许访问
            console.log('已登录，允许访问:', to.name)
            next()
        } else {
            // 未登录，重定向到登录页
            console.log('未登录，重定向到登录页')
            next({
                name: 'login',
                query: { redirect: to.fullPath } // 保存用户想要访问的页面
            })
        }
    } else {
        // 不需要认证的页面（如登录页）
        console.log('不需要认证的页面:', to.name)
        next()
    }
})

export default router
